<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query"  @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="adddialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scoped">
            <el-switch v-model="scoped.row.mg_state" active-color="#13ce66"
             inactive-color="#ff4949" @change="userStateChange(scoped.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scoped">
            <!-- 修改按钮 -->
            <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scoped.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scoped.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" @click="setRole(scoped.row)" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
       <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[10, 200, 300, 400]"
          :page-size="queryInfo.pagenum"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
    </el-pagination>
    </el-card>
    <!-- 添加对话框 -->
  <el-dialog
    title="添加用户"
    :visible.sync="adddialogVisible"
    :before-close="handleClose"
    width="40%">
    <!-- 内容主体区域 -->
      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
  <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogClose('addFormRef')">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
</el-dialog>
<!-- 删除对话框 -->
<el-dialog
  title="提示"
  :visible.sync="deletedialogVisible"
  width="40%"
  :before-close="deletehandleClose">
  <span>这是一段信息</span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="deletedialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="deletedialogVisible = false">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改用户对话框 -->
<el-dialog
  title="修改操作"
  :visible.sync="EditDialogVisible"
  width="40%"
  @close="editDialogClosed"
 >
  <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px" >
    <el-form-item label="用户名" >
      <el-input v-model="editForm.username" disabled></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
     <el-input v-model="editForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
     <el-input v-model="editForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="EditDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
</el-dialog>
<!-- 分配角色的对话框-->
<el-dialog
  title="分配角色"
  :visible.sync="setRoleDialogVisible"
  width="50%"
  @close="setRoleDialogClosed">
  <div>
    <p>当前的用户：{{userInfo.username}}</p>
    <p>当前的角色：{{userInfo.role_name}}</p>
    <!-- 角色下拉选择框 -->
    <p>分配新角色：
      <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option
         v-for="item in rolesList"
         :key="item.id"
         :label="item.roleName"
         :value="item.id">
       </el-option>
  </el-select></p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRole">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱账号规则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
      // 合法的邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法手机号
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
      // 查询参数
        query: '', // 查询参数
        pagenum: 1, // 开始页码
        pagesize: 10 // 结束页码
      },
      userList: [],
      total: 0,
      adddialogVisible: false, // 新增对话框
      deletedialogVisible: false, // 删除对话框
      EditDialogVisible: false, // 修改对话框
      // 添加用户表单的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 添加表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户账号长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户密码长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 分配角色对话框
      setRoleDialogVisible: false,
      // 需要被分配的用户角色信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 选中角色的id
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    /* 获取用户列表 */
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    /** 监听 pageSize 修改 */
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    /** 监听 页码值 改变的事件 */
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    /** 监听 switch 开关状态改变 */
    async userStateChange (userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/:${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        // 更新失败改回原来的状态
        userinfo.mg_state = !userinfo.mg_state
        this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    /* 关闭添加对话框,同时清空表单域 */
    adddialogClose (addFormName) {
      this.$refs[addFormName].resetFields()
      this.adddialogVisible = false
    },
    /* 关闭添加对话框 */
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(() => {
          // 关闭对话框
          this.adddialogVisible = false
          // 清空表单数据
          this.$refs.addFormRef.resetFields()
        }).catch(() => {})
    },
    /* 点击按钮，添加用户 */
    addUser () {
      // 表单预验证
      this.$refs.addFormRef.validate(async valid => {
        // 校验失败 直接返回
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户从失败')
        }
        this.$message.success('添加用户成功')
        // 隐藏添加对话框
        this.adddialogVisible = false
        // 重新查询数据
        this.getUserList()
      })
    },
    /* 删除对话框 */
    deletehandleClose () {
    },
    /* 修改用户对话框 */
    async showEditDialog (id) {
      // 打开修改对话框
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editForm = res.data
      this.EditDialogVisible = true
      console.log(this.editForm)
    },
    /* 关闭修改对话框 */
    editDialogClosed () {
      // 清空表单
      this.$refs.editFormRef.resetFields()
    },
    /* 修改用户信息 */
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        // 关闭修改对话框
        this.EditDialogVisible = false
        // 重新查询用户数据
        this.getUserList()
        // 提示修改成功
        this.$message.success('更新用户信息成功')
      })
    },
    /* 删除用户信息 */
    removeUserById (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
          return
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // 重新获取数据
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /* 分配角色 */
    async setRole (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取分配角色列表失败')
      }
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    /* 保存角色权限 */
    async saveRole () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择对应角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('分配新角色失败')
      }
      this.$message.success('保存新角色成功')
      // 重新查询角色列表
      this.getUserList()
      // 关闭对话框
      this.setRoleDialogVisible = false
    },
    /* 分配新角色关闭回调框 */
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>
